<?php

namespace app\admin\controller;

use app\admin\model\Order;
use app\BaseController;
use app\dic\DicOrder;
use app\dic\DicPublic;
use app\dic\DicSite;
use think\facade\Db;
use think\App;

class Taskordershopline extends BaseController
{
    protected $model = null;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new Order();
    }

    public function order()
    {
        $type = input('type');
        if (!$type) {
            return error('type不能为空');
        }
        $site_id = input('site_id');
        $where = [
            'site_type' => DicSite::$site_type_3,
            'status' => DicSite::$status_normal,
        ];
        if (!empty($site_id)) {
            $where['id'] = $site_id;
            $site = table('site')->where($where)->find();
        } else {
            $site = table('site')->where($where)->order(['task_updatetime_product' => 'asc'])->find();
        }
        $return = $this->deal_orders($site, $type);
        return success('操作成功', $return);
    }

    public function deal_orders($site, $type)
    {
        $url = $site['site_url'] . "/admin/openapi/v20231201/orders.json";
        if ($type == DicOrder::$type_4) {
            $last_order = table('order')
                ->where('site_id', $site['id'])
                ->order('yupdated_at desc')
                ->find();
            if ($last_order) {
                $updated_at_min = $last_order['yupdated_at'];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2023-07-01T00:00:00-07:00';
            }
            $url = $url . '?updated_at_min=' . $updated_at_min.'&limit=' . DicPublic::$task_limit_100;
        }
        if ($type == DicOrder::$type_3) {
            if (!empty($site['updatetime_order'])) {
                $created_at_max = $site['updatetime_order'];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', time());
                $created_at_max2 = date('H:i:s', time());
                $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-07:00';
            }
            $url = $url . '?created_at_min=' . $created_at_max.'&limit=' . DicPublic::$task_limit_100;
        }
        if ($type == DicOrder::$type_2) {
            $last_order = table('order')
                ->where('site_id', $site['id'])
                ->order('ycreated_at desc')
                ->find();
            if ($last_order) {
                $updated_at_min = $last_order['ycreated_at'];
                // $updated_at_mins = explode('T', $updated_at_min);
                // $updated_at_mins[0] = date('Y-m-d', strtotime("$updated_at_mins[0]-1day"));
                // $updated_at_min = $updated_at_mins[0] . 'T' . $updated_at_mins[1];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2021-07-01T00:00:00-07:00';
            }
            $url = $url . '?created_at_min=' . $updated_at_min.'&limit=' . DicPublic::$task_limit_100;
        }
        $url = $url . '&sort_condition=orderTime:desc&status=any';
        // halt($url);
        $data =  $this->geturl($url,$site['apisecret']);
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return 2;
            }
            // halt($data);
            $orders = $data['orders'];
            if (is_array($orders) && !empty($orders)) {
                date_default_timezone_set('Asia/Shanghai');
                $update_ordertime_data['updatetime_order'] = 0;
                foreach ($orders as  $order) {
                    $order_info = $this->model->where(['id' => $order['id']])->find();
                    $arr['id'] = $order['id'];
                    $arr['name'] = '#'.$order['name'];
                    $arr['number'] = $order['name'];
                    $arr['order_number'] = $order['name'];
                    $arr['ycreated_at'] = $order['created_at'];
                    $arr['yupdated_at'] = $order['updated_at'];
                    //改变时间
                    if (!empty($arr['ycreated_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $arr['ycreated_at']);
                        $arr['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                    }
                    $arr['created_at'] = strtotime($arr['created_at']);
                    //货币
                    $arr['currency'] = $order['currency'];
                    //支付状态
                    if (!empty($order['financial_status'])) {
                        $arr['financial_status'] = $order['financial_status'];
                    } else {
                        //自定义授权未完成
                        $arr['financial_status'] = DicOrder::$financial_status_unfulfilled;
                    }
                    $arr['ytotal_price'] = $order['current_total_price'];
                    $arr['total_price'] = $order['current_total_price'];
                    $arr['site_id'] = $site['id'];
                    if (!empty($order['tags'])) {
                        $arr['tags'] = $order['tags'];
                    } else {
                        $arr['tags'] = '暂无';
                    }
                    //如果接口返回空 则改成未发货
                    if (!empty($order['fulfillment_status'])) {
                        $arr['fulfillment_status'] = $order['fulfillment_status'];
                    } else {
                        // $arr['fulfillment_status'] = DicOrder::$fulfillment_status_unshipped;
                    }

                    if ($order_info) {
                        // if ($order_info['yupdated_at'] !== $arr['yupdated_at']) {
                            $this->model->where(['id' => $order['id']])->update($arr);
                        // }
                    } else {
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $this->model->insert($arr);
                    }
                    if (!empty($site['updatetime_order'])) {
                        //直接截取获得时间戳
                        $ycreated_atx = str_replace('T', ' ', $site['updatetime_order']);
                        $ycreated_atx = substr($ycreated_atx, 0, strripos($ycreated_atx, '-'));
                        $ycreated_atx = strtotime($ycreated_atx);

                        if ($ycreated_atx < $arr['created_at']) {
                            if (!empty($zcreated_at)) {
                                if ($arr['created_at'] > $zcreated_at) {
                                    $zcreated_at = $arr['created_at'];
                                    $update_ordertime_data['updatetime_order'] = $arr['ycreated_at'];
                                }
                            } else {
                                $zcreated_at = $arr['created_at'];
                                $update_ordertime_data['updatetime_order'] = $arr['ycreated_at'];
                            }
                        } else {
                            $update_ordertime_data['updatetime_order'] = $site['updatetime_order'];
                        }
                    } else {
                        $update_ordertime_data['updatetime_order'] = $arr['ycreated_at'];
                    }
                }
            }
        }
        $update_ordertime_data['task_updatetime_product'] = time();
        table('site')
            ->where('id', $site['id'])
            ->update($update_ordertime_data);
        return 1;
    }

    function geturl($url,$apisecret)
    {
        $headerArray = array("Content-Type:application/json;", 'Authorization:Bearer ' . $apisecret);
        // halt($headerArray);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function posturl($url, $data = array(), $iscustom = null)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['apikey'];
        $apisecret = $iscustom['apisecret'];

        $headerArray = array("Content-Type:application/json;", 'Authorization:Bearer ' . base64_encode("$apikey:$apisecret"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    
    /**
     *shopline数据
     */
    public function update_order($id = null)
    {
        if (!empty($id)) {
            $orders = table('order')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $site_ids = input('site_ids');
            $where = array();
            if (!empty($site_ids)) {
                $where['site_id'] = $site_ids;
            } else {
                //从7店铺开始更新
                // $where['site_id']  = array('egt', 7);
                $where[]  = ['site_id', '=', 109];
            }
            $thismonth = date('m');
            $thisyear = date('Y');
            if ($thismonth == 1) {
                $lastmonth = 10;
                $lastyear = $thisyear - 1;
            } elseif ($thismonth == 2) {
                $lastmonth = 11;
                $lastyear = $thisyear - 1;
            } elseif ($thismonth == 3) {
                $lastmonth = 12;
                $lastyear = $thisyear - 1;
            } else {
                $lastmonth = $thismonth - 2;
                $lastyear = $thisyear;
            }
            $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
            $b_time = strtotime($lastStartDay);
            $e_time = time();
            // $where['created_at'] = array(array('egt', $b_time), array('elt', $e_time));
            // $where[] = ['created_at', '>=', $b_time];
            // $where[] = ['created_at', '<=', $e_time];
            $orders = table('order')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('5')
                ->select()->toarray();
        }
        if (!empty($orders)) {
            $row = array();
            $site = table('site')
                ->where('id', 109)
                ->find();
            foreach ($orders as $order) {
                $url = $site['site_url'] . "/admin/openapi/v20231201/orders.json";
                $url = $url . '?ids=' . $order['id'];
                $url = $url . '&status=any';
                $data =  $this->geturl($url,$site['apisecret']);
                $data = json_decode($data, true);
                $row = array();
                if (isset($data['orders'][0])) {
                    $order_new = $data['orders'][0];
                    // halt($order_new);
                    //新增商品详情
                    if (isset($order_new['line_items'])) {
                        $line_items = $order_new['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {
                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['price'] = $line_item['price'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                $arr['order_id'] = $order['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $order['created_at'];
                                $order_quantity = table('order_quantity')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->where('product_id', $arr['product_id'])
                                    ->find();
                                if (empty($order_quantity)) {
                                    table('order_quantity')->insert($arr);
                                } else {
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $arr['user_id'] = $product_tags;
                                        table('order_quantity')
                                            ->where('variant_id', $arr['variant_id'])
                                            ->where('order_id', $arr['order_id'])
                                            ->where('product_id', $arr['product_id'])
                                            ->update($arr);
                                    }
                                }
                                //商品
                                $order_product = table('order_product')->where('product_id', $arr['product_id'])->find();
                                if (empty($order_product)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['site_id'] = $order['site_id'];
                                    $product['product_name'] = $arr['title'];
                                    table('order_product')->insert($product);
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $order_sku = table('order_sku')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($order_sku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['site_id'] = $order['site_id'];
                                        table('order_sku')
                                            ->insert($sku_arr);
                                    } else {
                                        //修改SKU
                                        $sku2['sku'] = $arr['sku'];
                                        table('order_sku')->where('id', $order_sku['id'])->update($sku2);
                                    }
                                }
                            }
                        }
                    }
                    //新增商品物流单
                    if (isset($order_new['fulfillments'])) {
                        $fulfillments = $order_new['fulfillments'];
                        if (!empty($fulfillments)) {
                            table('order_fulfillments')
                                ->where('order_id', $order['id'])
                                ->delete();
                            foreach ($fulfillments as $line_item) {
                                $arr2['tracking_ids'] = $line_item['id'];
                                $arr2['name'] = $line_item['name'];
                                $arr2['tracking_number'] = $line_item['tracking_number'];
                                $arr2['tracking_company'] = $line_item['tracking_company'];
                                $arr2['order_id'] = $line_item['order_id'];
                                $arr2['createtime'] = time();
                                $arr2['updatetime'] = time();
                                table('order_fulfillments')->insert($arr2);
                                $row['tracking_number'] = $line_item['tracking_number'];
                                $row['tracking_company'] = $line_item['tracking_company'];
                            }
                        }
                    }

                    //联系人
                    if (isset($order_new['customer']['email'])) {
                        $row['email'] = $order_new['customer']['email'];
                    } else {
                        $row['email'] = '';
                    }

                    if (isset($order_new['shipping_address']['name'])) {
                        $row['shipping_name'] = $order_new['shipping_address']['name'];
                    } else {
                        $row['shipping_name'] = '';
                    }
                    if (isset($order_new['shipping_address']['phone'])) {
                        $row['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "", $order_new['shipping_address']['phone']);
                    } else {
                        $row['phone'] = '';
                    }
                    if (isset($order_new['shipping_address']['province'])) {
                        $row['province'] = $order_new['shipping_address']['province'];
                    } else {
                        $row['province'] = '';
                    }
                    if (isset($order_new['shipping_address']['city'])) {
                        $row['city'] = $order_new['shipping_address']['city'];
                    } else {
                        $row['city'] = '';
                    }
                    if (isset($order_new['shipping_address']['zip'])) {
                        $row['zip'] = $order_new['shipping_address']['zip'];
                    } else {
                        $row['zip'] = '';
                    }
                    if (isset($order_new['shipping_address']['address1'])) {
                        $row['address1'] = $order_new['shipping_address']['address1'];
                    } else {
                        $row['address1'] = '';
                    }
                    if (isset($order_new['shipping_address']['country_code'])) {
                        $row['country_code'] = $order_new['shipping_address']['country_code'];
                    } else {
                        $row['country_code'] = '';
                    }

                    if (!empty($order_new['tags'])) {
                        $row['tags'] = $order_new['tags'];
                    } else {
                        $row['tags'] = '暂无';
                    }
                }
                $row['updateordertime'] = time();
                //同步物流消息
                table('order')
                    ->where('id', $order['id'])
                    ->update($row);
            }
            return success('操作成功');
        } else {
            return error('未找到相关订单');
        }
    }
}
